package com.seecen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.seecen.mapper.RecipeCategoryRelationMapper;
import com.seecen.pojo.RecipeCategoryRelation;
import com.seecen.pojo.Recipes;
import com.seecen.service.RecipesService;
import com.seecen.mapper.RecipesMapper;
import com.seecen.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.UUID;

/**
 * @author W
 * @description 针对表【t_recipes(菜谱信息表)】的数据库操作Service实现
 * @createDate 2025-07-21 12:57:25
 */
@Service
public class RecipesServiceImpl extends ServiceImpl<RecipesMapper, Recipes>
        implements RecipesService{
    // 保存图片的目录（相对于项目根目录）
    private static final String UPLOAD_DIR = "frontend/src/assets/img/";

    // 用于生成随机文件名的字符集
    private static final String CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static final int FILENAME_LENGTH = 8; // 随机文件名长度
    private static final Random RANDOM = new Random();

    @Autowired
    private RecipesMapper recipesMapper;

    @Autowired
    private RecipeCategoryRelationMapper recipeCategoryRelationMapper;

    @Override
    public String saveImage(MultipartFile file) throws IOException {
        System.out.println("开始保存图片");
        // 1. 检查上传目录是否存在，不存在则创建
        File uploadDir = new File(UPLOAD_DIR);
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 2. 生成简短的随机文件名
        String originalFilename = file.getOriginalFilename();
        String fileExtension = "";
        String randomFilename = generateRandomFilename();

        if (originalFilename != null && originalFilename.contains(".")) {
            fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        originalFilename = randomFilename + fileExtension;

        // 记录生成的文件名和完整URL长度
        String imageUrl = "/src/assets/img/" + originalFilename;
        System.out.println("生成的文件名: " + originalFilename);
        System.out.println("完整URL: " + imageUrl);
        System.out.println("URL长度: " + imageUrl.length());

        // 3. 保存文件到指定目录
        Path filePath = Paths.get(UPLOAD_DIR + originalFilename);
        Files.write(filePath, file.getBytes());

        // 4. 返回图片的访问路径（前端通过 /src/assets/img/ 访问）
        System.out.println("图片保存成功" + "url:" + filePath.toString());
        return imageUrl;
    }

    /**
     * 生成指定长度的随机文件名
     * @return 随机文件名
     */
    private String generateRandomFilename() {
        StringBuilder sb = new StringBuilder(FILENAME_LENGTH);
        for (int i = 0; i < FILENAME_LENGTH; i++) {
            sb.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length())));
        }
        return sb.toString();
    }

    @Override
    public Result getRecipesAll() {
        List<Recipes> recipesList = recipesMapper.selectList(null);
        return Result.ok(recipesList);
    }

    @Override
    public Result recipesById(Integer id) {
        // 1. 参数校验
        if (id == null || id <= 0) {
            return Result.ok("菜谱 ID 不能为空或小于等于 0");
        }

        // 2. 查询菜谱基本信息
        Recipes recipes = recipesMapper.selectById(id);
        if (recipes == null) {
            return Result.ok("菜谱不存在");
        }
        HashMap map = new HashMap();
        map.put("recipes",recipes);

        return Result.ok(map);
    }

    @Override
    public List<Recipes> searchRecipesByKeyword(String keyword) {
        // 根据关键字搜索菜谱（在菜谱名称中搜索）
        QueryWrapper<Recipes> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("recipes_name", keyword);
        return recipesMapper.selectList(queryWrapper);
    }

    // 保存菜谱和分类的关联关系
    @Override
    public void saveRecipeWithCategory(Recipes recipe, Integer categoryId) {
        // 参数校验
        if (recipe == null) {
            throw new IllegalArgumentException("菜谱对象不能为空");
        }
        if (StringUtils.isEmpty(recipe.getRecipesName())) {
            throw new IllegalArgumentException("菜谱名称不能为空");
        }
        if (categoryId == null) {
            throw new IllegalArgumentException("分类ID不能为空");
        }
        if (StringUtils.isEmpty(recipe.getRecipesUrl())) {
            throw new IllegalArgumentException("封面图片URL不能为空");
        }

        // 设置默认用户ID（实际项目中应该从JWT token中获取）
        if (recipe.getUserId() == null) {
            recipe.setUserId(1); // 设置默认用户ID为1
        }

        // 设置创建时间
        recipe.setCreateTime(new Date());
        // 注意：updateTime字段现在用于存储菜品时长（分钟），不再表示更新时间

        // 保存菜谱基本信息
        this.save(recipe); // 保存到 t_recipes 表

        // 保存菜谱与分类的关联关系
        RecipeCategoryRelation relation = new RecipeCategoryRelation();
        relation.setRecipeId(recipe.getRecipesId());
        relation.setCategoryId(categoryId);
        recipeCategoryRelationMapper.insert(relation);
    }
}